package com.budwk.app.sqfwV2.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.constants.DictConstants;
import com.budwk.app.sqfw.enums.DownLoadFileNameEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseTemplateExcelGenerator;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowPdfParamForController;
import com.budwk.app.sqfwDoc.dto.CompleteFlowTemplateCodeUpdateDTO;
import com.budwk.app.sqfwDoc.dto.TemplateCodeUpdateDTO;
import com.budwk.app.sqfwV2.component.ShawenTownComponent;
import com.budwk.app.sqfwV2.component.SummarySafetyCommponent;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownFileTypesResVo;
import com.budwk.app.sqfwV2.dto.shawenTown.ShawenTownSafetyPdfDTO;
import com.budwk.app.sqfwV2.dto.shawenTown.UpdateVisitPicturesVo;
import com.budwk.app.sqfwV2.service.ShawenTownSafetyService;
import com.budwk.app.sqfwV2.service.ShopsBaseInfoService;
import com.budwk.app.sqfwV2.service.shawenTown.ShawenTownSafetyExcelService;
import com.budwk.app.sqfwV2.service.shawenTown.ShawenTownSafetyPdfService;
import com.budwk.app.sys.services.SysDictService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.sys.vo.SysDictVO;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@IocBean
public class ShawenTownSafetyServiceImpl implements ShawenTownSafetyService {

    @Inject
    private ShawenTownSafetyPdfService shawenTownSafetyPdfService;
    @Inject
    private ShawenTownSafetyExcelService shawenTownSafetyExcelService;
    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;
    @Inject
    private SysDictService sysDictService;
    @Inject
    private ShopsBaseInfoService shopsBaseInfoService;
    @Inject
    private SysUserService userService;
    @Inject
    private ShawenTownComponent shawenTownComponent;
    @Inject
    private SummarySafetyCommponent summarySafetyCommponent;

    @Override
    public void submitData(TemplateCodeUpdateDTO dto) {
        CompleteFlowPdfParamForController param = new CompleteFlowPdfParamForController();
        // 组装参数
        CompleteFlowTemplateCodeUpdateDTO codeUpdateDTO = new CompleteFlowTemplateCodeUpdateDTO();
        codeUpdateDTO.setCompleteFlow(dto.getCompleteFlow());
        codeUpdateDTO.setFormSummary(dto.getFormSummary());
        param.setCompleteFlowDataDTO(codeUpdateDTO);
        param.setUserId(SecurityUtil.getUserId());

        summarySafetyCommponent.createOneTask(dto, null, ShawenTownComponent.FILL_TYPE);
        shawenTownSafetyPdfService.createPdfAndMsg(param);
    }

    @Override
    public Result<?> reGeneratePDF(String sqfwFlowId) {
        CompleteFlowPdfParamForController param = new CompleteFlowPdfParamForController();
        param.setCompleteFlowId(sqfwFlowId);
        shawenTownSafetyPdfService.reCreatePdfAndMsg(param);
        return Result.success();
    }

    @Override
    public Result<?> downExcelLedger(DownExcelLedgerReqVo reqVo) {
        List<ExcelCreateConfig> excelConfigList = CommonComponent.getExcelConfigList(reqVo);
        List<Sqfw_formSummary_new> list = new ArrayList<>();
        if (CollectionUtil.isEmpty(reqVo.getSqfwIds())) {
            if (!reqVo.isDownTemplate()) {
                list = CommonComponent.querySummarys(null, ShawenTownComponent.FILL_TYPE);
                if (CollectionUtil.isEmpty(list)) {
                    return Result.success();
                }
            }
        }
        List<GenerateExcelUrlVO> generateExcelUrlVOS = shawenTownSafetyExcelService.downExcelLedger(excelConfigList, SecurityUtil.getUserId(), reqVo.getSqfwIds(), list);
        return Result.data(generateExcelUrlVOS);
    }

    @Override
    public Result<?> listByConditionKey(String address, String placeName) {
        if (StringUtils.isNotEmpty(address)) {
            return shawenTownComponent.listByConditionAddress(address);
        }
        if (StringUtils.isNotEmpty(placeName)) {
            return shawenTownComponent.listByConditionPlaceName(placeName);
        }
        return Result.success();
    }

    @Override
    public Result<List<DownFileTypesResVo>> listDownFileTypes(String sqfwId) {
        // 1 获取所有字典数据
        List<SysDictVO> vos = sysDictService.listDictByCode(DictConstants.SHAWEN_EXCEL_COLLECTION);
        //2 按照社区服务id查询数据
        List<Sqfw_formSummary_new> list = null;
        if (StringUtils.isEmpty(sqfwId)) {
            list = CommonComponent.querySummarys(null, ShawenTownComponent.FILL_TYPE);
        } else {
            list = sqfwFormsummaryNewService.queryBySqfwIdAndType(sqfwId, ShawenTownComponent.FILL_TYPE);
        }
        // 检查数据是否可生成
        List<DownFileTypesResVo> results = new ArrayList<>();
        for (SysDictVO vo : vos) {
            getDownFileTypesResVo(results, list, vo);
        }
        // 排序(按照修改时间升序)
        List<DownFileTypesResVo> resVos = results.stream().sorted(Comparator.comparing(DownFileTypesResVo::getLocation)).collect(Collectors.toList());
        System.out.println("------------" + results.size());
        // 安全排查表pdf
        DownFileTypesResVo resVo = new DownFileTypesResVo();
        resVo.setFileName(DownLoadFileNameEnum.SHAWEN_INVESTIGATE_RENOVATE.getName() + ".pdf").
                setFileCode(DownLoadFileNameEnum.SHAWEN_INVESTIGATE_RENOVATE.getCode()).setHiveData(list.size() > 0)
                .setCreatedAt(System.currentTimeMillis())
                .setFileType("pdf");
        resVos.add(resVo);
        return Result.data(resVos);
    }

    @Override
    public void downWordTemplate(HttpServletResponse response) {
        String fileName = DownLoadFileNameEnum.SHAWEN_INVESTIGATE_RENOVATE.getName() + ".docx";
        String filepath = CommonFormOfficeUtils.getTemplatePathByOS("sqfwV2/shawenTown/template/shawenTownSafeWordTemplate.docx");
        // 下载文件
        CommonComponent.downFile(response, filepath, fileName);
    }

    @Override
    public Result<Sqfw_formSummary_new> getSummaryDetail(String sqfwFlowId) {
        if (StringUtils.isEmpty(sqfwFlowId)) {
            return Result.success();
        }
        Sqfw_formSummary_new summaryNew = sqfwFormsummaryNewService.fetch(Cnd.where(Sqfw_formSummary_new::getSqfwFlowId, "=", sqfwFlowId));
        return Result.data(summaryNew);
    }

    @Override
    public Result<?> updateVisitPictures(UpdateVisitPicturesVo picturesVo) {
        // 1 校验
        ShawenTownComponent.checkUpdateVisitPictures(picturesVo);
        // 2 业务代码实现
        Sqfw_formSummary_new summary = sqfwFormsummaryNewService.fetch(picturesVo.getId());
        if (summary == null) {
            throw new AppException("业务异常，请检查id是否传递正确！");
        }
        ShawenTownSafetyPdfDTO pdf = JSONObject.parseObject(summary.getParamData(), ShawenTownSafetyPdfDTO.class);
        pdf.setVisitPictures(StringUtils.isNotEmpty(picturesVo.getVisitPictures()) ? picturesVo.getVisitPictures() : "");
        summary.setParamData(JSONObject.toJSONString(pdf));
        sqfwFormsummaryNewService.updateIgnoreNull(summary);
        // 调用重新生成pdf接口 实现修改操作
        reGeneratePDF(summary.getSqfwFlowId());
        return Result.success();
    }

    private void getDownFileTypesResVo(List<DownFileTypesResVo> results, List<Sqfw_formSummary_new> list, SysDictVO vo) {
        DownFileTypesResVo resVo = new DownFileTypesResVo();
        BaseTemplateExcelGenerator service = ShawenTownComponent.getService(vo.getCode());
        List<Sqfw_formSummary_new> newList = service.generateNewData(list);
        resVo.setFileCode(vo.getCode()).setFileName(vo.getName())
                .setHiveData(newList.size() > 0)
                .setCreatedAt(vo.getCreatedAt())
                .setUpdateAt(vo.getUpdatedAt())
                .setFileType("excel")
                .setLocation(vo.getLocation());
        results.add(resVo);
    }
}
